package com.yungu.swift.monitor.config;

import com.yungu.swift.monitor.license.IpAndMac;
import com.yungu.swift.utils.DateUtils;
import com.yungu.swift.utils.MapUtils;
import de.codecentric.boot.admin.event.ClientApplicationEvent;
import de.codecentric.boot.admin.event.ClientApplicationStatusChangedEvent;
import de.codecentric.boot.admin.notify.AbstractEventNotifier;
import de.codecentric.boot.admin.notify.RemindingNotifier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.client.RestTemplate;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author : cuixiuyin
 * @date : 2020/1/7
 */
@Configuration
@EnableScheduling
public class NotifierConfig {

    private static final Logger log = LoggerFactory.getLogger(NotifierConfig.class);

    @Autowired
    private RemindingNotifier remindingNotifier;
    @Autowired
    private RestTemplate restTemplate;

    @Bean
    @Primary
    public RemindingNotifier remindingNotifier() {

        RemindingNotifier remindingNotifier = new RemindingNotifier(new AbstractEventNotifier() {

            @Override
            protected void doNotify(ClientApplicationEvent event) throws Exception {
                if (event instanceof ClientApplicationStatusChangedEvent) {
                    ClientApplicationStatusChangedEvent changedEvent = (ClientApplicationStatusChangedEvent) event;
                    // 首次启动不通知
                    if ("UNKNOWN".equals(changedEvent.getFrom().getStatus())) {
                        return;
                    }
                    log.info("Application {} ({}) is {}", event.getApplication().getName(), event.getApplication().getId(), changedEvent.getTo().getStatus());
                    StringBuilder content = new StringBuilder();
                    content.append("<font color=\"warning\">").append("【应用状态变更通知】").append("</font>").append("\n");
                    content.append("> 机器：").append(IpAndMac.getInternetIp()).append("\n");
                    content.append("> 应用：").append(changedEvent.getApplication().getName()).append("\n");
                    content.append("> 状态：")
                            .append(changedEvent.getFrom().getStatus())
                            .append(" -> ")
                            .append(changedEvent.getTo().getStatus())
                            .append("\n");
                    content.append("> 时间：").append(DateUtils.format(new Date(changedEvent.getTimestamp()))).append("\n");

                    Map<String, Object> paramMap = new HashMap<>(4);
                    paramMap.put("msgtype", "markdown");
                    paramMap.put("markdown", MapUtils.build("content", content.toString()));
                    restTemplate.postForObject("https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=08b7fd13-453b-4997-9b90-e5286dffe3f3", paramMap, String.class);
                } else {
                    log.info("Application {} ({}) {}", event.getApplication().getName(), event.getApplication().getId(), event.getType());
                }
            }
        });
        remindingNotifier.setReminderPeriod(TimeUnit.HOURS.toMillis(12L));
        return remindingNotifier;
    }

    /**
     * 每隔一分钟检查还有那些需要进行提醒
     */
    @Scheduled(fixedRate = 1_000L)
    public void remind() {
        remindingNotifier.sendReminders();
    }
}
